#!/bin/bash

# enable_maintenance.sh - 启用维护模式（支持 HTTPS + 动态路径）

# 获取脚本所在目录（兼容软链接）
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
MAINTENANCE_PAGE="$PROJECT_ROOT/html/maintenance.html"
NGINX_ROOT="/usr/share/nginx/html"
CERT_DIR="/etc/nginx/ssl"
SSL_KEY="$CERT_DIR/bingbingyihao.cn.key"
SSL_CERT="$CERT_DIR/bingbingyihao.cn.pem"

echo "🚧 正在启用维护模式（支持 HTTPS）..."

# 检查维护页面是否存在
if [ ! -f "$MAINTENANCE_PAGE" ]; then
  echo "❌ 错误：未找到维护页面 -> $MAINTENANCE_PAGE"
  exit 1
fi

# 检查证书是否存在（用于 HTTPS）
if [ ! -f "$SSL_KEY" ] || [ ! -f "$SSL_CERT" ]; then
  echo "⚠️  警告：SSL 证书缺失，HTTPS 将无法正常工作"
  echo "     预期路径: $SSL_KEY 和 $SSL_CERT"
  echo "     若未启用 HTTPS 可忽略此警告，否则请先运行 nginx_mod_https.sh"
fi

# 创建临时维护用 Nginx 配置
TEMP_CONF="/tmp/nginx-maintenance.conf"

cat > "$TEMP_CONF" << EOF
user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '\$remote_addr - \$remote_user [\$time_local] "\$request" '
                      '\$status \$body_bytes_sent "\$http_referer" '
                      '"\$http_user_agent" "\$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    keepalive_timeout  65;

    gzip  on;
    gzip_types text/plain application/json application/javascript text/css;

    # ========== 维护模式：HTTP 自动跳转 HTTPS & 统一拦截 ==========
    server {
        listen 80;
        server_name bingbingyihao.cn www.bingbingyihao.cn localhost;

        # 强制跳转 HTTPS（如果需要；也可直接返回维护页）
        return 301 https://\$host\$request_uri;
    }

    # ========== 维护模式：HTTPS 用户端 (443) ==========
    server {
        listen 443 ssl http2;
        server_name bingbingyihao.cn www.bingbingyihao.cn;

        root $NGINX_ROOT/maintenance;
        index maintenance.html;

        # SSL 配置（复用主站证书）
        ssl_certificate      $SSL_CERT;
        ssl_certificate_key  $SSL_KEY;
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384;
        ssl_prefer_server_ciphers off;
        ssl_session_cache shared:SSL:10m;
        ssl_session_timeout 10m;

        add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
        add_header X-Frame-Options DENY;
        add_header X-Content-Type-Options nosniff;

        location / {
            try_files /maintenance.html =503;
        }

        location /api/ {
            return 503 '{\"error\": \"Service Unavailable\", \"message\": \"System is under maintenance.\"}';
            add_header Content-Type "application/json";
            add_header Cache-Control "no-store, no-cache";
        }
    }

    # ========== 维护模式：HTTPS 管理端 (10000) ==========
    server {
        listen 10000 ssl;
        server_name localhost;

        root $NGINX_ROOT/maintenance;
        index maintenance.html;

        # 复用相同证书
        ssl_certificate      $SSL_CERT;
        ssl_certificate_key  $SSL_KEY;
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers HIGH:!aNULL:!MD5;

        location / {
            try_files /maintenance.html =503;
        }

        location /api/ {
            return 503 '{\"error\": \"Service Unavailable\", \"message\": \"System is under maintenance.\"}';
            add_header Content-Type "application/json";
            add_header Cache-Control "no-store, no-cache";
        }
    }
}
EOF

# 创建维护资源目录并复制页面
mkdir -p "$NGINX_ROOT/maintenance"
cp "$MAINTENANCE_PAGE" "$NGINX_ROOT/maintenance/maintenance.html"
echo "✅ 维护页面已部署到: $NGINX_ROOT/maintenance/"

# 替换 Nginx 主配置
sudo cp "$TEMP_CONF" /etc/nginx/nginx.conf
echo "📝 已写入新配置: /etc/nginx/nginx.conf"

# 测试并重载 Nginx
echo "🔄 正在测试 Nginx 配置..."
sudo nginx -t
if [ $? -eq 0 ]; then
    sudo systemctl reload nginx || {
        echo "⚠️  reload 失败，正在尝试 restart..."
        sudo systemctl restart nginx
    }
    echo "✅ 维护模式已启用！"
    echo "🌐 所有访问将被拦截："
    echo "   - https://bingbingyihao.cn"
    echo "   - https://bingbingyihao.cn:10000"
else
    echo "❌ Nginx 配置测试失败，请检查 /tmp/nginx-maintenance.conf"
    exit 1
fi
